package com.czl.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czl.entity.Student;
import com.czl.mapper.StudentMapper;
import com.czl.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.PageResult;
import utils.R;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    //查询所有学生
    @Override
    public List<Student> selectAll() {

        return studentMapper.selectList(null);
    }
    //分页查询
    @Override
    public PageResult<Student> selectByPage(Integer page, Integer pageSize){
        IPage<Student> pages=new Page<Student>(page, pageSize);

        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();

        IPage<Student> studentIPage = studentMapper.selectPage(pages, queryWrapper);

        PageResult<Student> studentPageResult = new PageResult<>();
        studentPageResult.setRows(studentIPage.getRecords());
        studentPageResult.setTotal(studentIPage.getTotal());
//        System.out.println(studentIPage);
        return studentPageResult;
    }

    @Override
    public PageResult<Student> selectByCondition(Integer page, Integer pageSize, Student student) {
        //启动分页
        IPage<Student> page1 = new Page<>(page, pageSize);
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        //检查stuName是否非空
        if(StrUtil.isNotBlank(student.getStuName())){
            queryWrapper.like("stuName",student.getStuName());
        }
        if(student.getStuAge() >0){
           queryWrapper.eq("stuAge",student.getStuAge());
        }
        IPage <Student>  students = studentMapper.selectPage(page1,queryWrapper);
        // 转换为定义的统一数据返回格式的PageResult对象
        return new PageResult<>(students.getRecords(),students.getTotal());
    }

    @Override
    public int addStudent(Student student) {
        try {
            return studentMapper.insert(student);
        }catch( Exception e){
            return 0;
        }
    }
}
